/**
 * 
 */
package com.dm.controller;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.dm.entity.CompanyGroupInfoDO;
import com.dm.entity.CompanyInfoDO;
import com.dm.entity.PerationLogDo;
import com.dm.entity.SysUserDO;
import com.dm.query.QueryCompanyGroupInfo;
import com.dm.query.QueryCompanyInfo;
import com.dm.query.QuerySysUser;
import com.dm.service.CompanyGroupInfoService;
import com.dm.service.CompanyInfoService;
import com.dm.service.PerationLogService;
import com.dm.service.SysUserService;
import com.dm.utils.HttpClient;
import com.dm.utils.RespsonseResult;
import com.dm.utils.SysInfoUtil;

/**  
 * @ClassName: UserController  
 * @Description: TODO(这里用一句话描述这个类的作用)  
 * @author qiuxl24710  
 * @date 2019年8月27日  
 *    
 */
@Controller
@RequestMapping("user")
public class SysUserController {
	
	private static Logger logger = LoggerFactory.getLogger(SysUserController.class);

	
	@Autowired
	SysUserService sysUserService ; 
	
	@Autowired
	CompanyGroupInfoService companyGroupInfoService ; 
	
	@Autowired
	CompanyInfoService companyInfoService ;
	
	@Autowired
	PerationLogService serationLogService ;
	
	
	@RequestMapping("adduser")
	public @ResponseBody Object addUser(HttpServletRequest request,QuerySysUser querySysUser){
		 SysUserDO user = (SysUserDO) request.getSession().getAttribute("user");
		 logger.info("添加用户,操作人："+user.getName());
		 RespsonseResult result = new RespsonseResult();
		 try {
			 if(StringUtils.isBlank(querySysUser.getCode())
					 ||StringUtils.isBlank(querySysUser.getPassword())
					 ||StringUtils.isBlank(querySysUser.getCompanyInfo())
					 ||StringUtils.isBlank(querySysUser.getName())
					 ||querySysUser.getType()==null){
				 result.setMsg("必填项不能为空");
				 return JSON.toJSON(result);    
			 }
			 
			//企业人员
			 if(querySysUser.getType() > 2){
				 QueryCompanyInfo qcInfo = new QueryCompanyInfo();
				 qcInfo.setCompanyCode(querySysUser.getCompanyInfo());
				 if(companyInfoService.selectOneCompanyInfo(qcInfo)== null){
					 result.setMsg("该企业不存在");
					 return JSON.toJSON(result);
				 }
			 }
			 
			 if(!checkPermission(user,querySysUser)){
				 result.setMsg("权限不足");
				 return JSON.toJSON(result);    
			 }
			 
			 QuerySysUser qsUser = new QuerySysUser();
			 qsUser.setCode(querySysUser.getCode());
			 SysUserDO codeUser = sysUserService.selectOneSysUser(qsUser);
			 if(codeUser != null){
				 result.setMsg("该账号已存在");
				 return JSON.toJSON(result);    
			 }
			 CompanyInfoDO cInfo = new CompanyInfoDO();
			 //运维人员,查询该分组是否存在
			 if(querySysUser.getType() < 3 ){
				 QueryCompanyGroupInfo cgInfo= new QueryCompanyGroupInfo();
				 cgInfo.setGroupCode(querySysUser.getCompanyInfo());
				 if(companyGroupInfoService.selectOneCompanyGroupInfo(cgInfo) == null){
					 result.setMsg("该企业分组不存在");
					 return JSON.toJSON(result);    
				 }
			 }
			 //检验完毕，开始插入
			 SysUserDO insertUser = new SysUserDO(querySysUser);
			 sysUserService.insertSysUser(insertUser);
			 if(user.getType() < 3){
				 insertLog(user,insertUser,null,"添加账号");
			 }
			 result.setMsg("插入成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("插入出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
		
		
	}
	
	@RequestMapping("selectuser")
	public @ResponseBody Object selectUser(HttpServletRequest request,QuerySysUser querySysUser){
		 SysUserDO userInfo = (SysUserDO) request.getSession().getAttribute("user");
		 logger.info("查询用户列表,操作人："+userInfo);
		 RespsonseResult result = new RespsonseResult();
		 try {
			 //查询出所有该分组下的人
			 List< CompanyInfoDO > companyData = new ArrayList<CompanyInfoDO>();
			 QueryCompanyInfo qcInfo = new QueryCompanyInfo() ; 
			 List<String> companyCodes = new ArrayList<String>();
			 if(userInfo.getType() != 0){
				 if(userInfo.getType() < 3){
					qcInfo.setGroupCode(userInfo.getCompanyInfo());
					companyData = companyInfoService.selectCompanyInfoList(qcInfo);
					for(CompanyInfoDO each : companyData){
						companyCodes.add(each.getCompanyCode());
					}
					querySysUser.setWxidList(companyCodes);
				 }else if(userInfo.getType() == 3){
					 qcInfo.setCompanyCode(userInfo.getCompanyInfo());
				 }else{
					 qcInfo.setCompanyCode(userInfo.getCompanyInfo());
					 querySysUser.setUserId(userInfo.getUserId());   
				 }
			 }
			 if(userInfo.getType() > 2 ){
				 companyData = companyInfoService.selectCompanyInfoList(qcInfo);
			 }
			 querySysUser.setOrderByClause("user_id");
			 List<SysUserDO> data = sysUserService.selectSysUserList(querySysUser);
			 for(SysUserDO u : data){
				 if(userInfo.getType() == 0 ){
					 u.setCompanyName("文马科技");
				 }else if(u.getType()<3 ){
					 QueryCompanyGroupInfo q =  new QueryCompanyGroupInfo();
					 q.setGroupCode(u.getCompanyInfo());
					 CompanyGroupInfoDO companyGroupInfoDO = companyGroupInfoService.selectOneCompanyGroupInfo(q);
					 u.setCompanyName(companyGroupInfoDO.getGroupName()+" 运维人员");
				 }else{
					 for(CompanyInfoDO each : companyData){
						 if(u.getType()>2 &&each.getCompanyCode().equals(u.getCompanyInfo())){
							 u.setCompanyName(each.getCompanyName());
						 }
					 } 
				 }
				 
			 }
			 int count = sysUserService.countSysUserList(querySysUser);
			 result.putOtherInfo("count",count);
			 result.setData(data);
			 result.setMsg("查询成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("查询出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
		
		
	}
	
	@RequestMapping("moduser")
	public @ResponseBody Object moduser(HttpServletRequest request,QuerySysUser querySysUser){
		 SysUserDO user = (SysUserDO) request.getSession().getAttribute("user");
		 logger.info("用户信息修改，操作人："+user.getName());
		 RespsonseResult result = new RespsonseResult();
		 try {
			 if(StringUtils.isBlank(querySysUser.getPassword())
					 && StringUtils.isBlank(querySysUser.getName())
					 && StringUtils.isBlank(querySysUser.getPic()) 
					 && StringUtils.isBlank( querySysUser.getPhone())){
				 result.setMsg("未输入修改信息");
				 return JSON.toJSON(result);    
			 }
			 SysUserDO upUser = new SysUserDO(querySysUser);
			 upUser.setUserId(user.getUserId());
			 sysUserService.updateSysUserByUserId(upUser);
			 if(!StringUtils.isBlank(querySysUser.getName())){
				 serationLogService.upLogByUserId(upUser);
			 }
			 result.setMsg("修改成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("修改出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
	}
	
	@RequestMapping("modAccount")
	public @ResponseBody Object modAccount(HttpServletRequest request,QuerySysUser querySysUser){
		 SysUserDO user = (SysUserDO) request.getSession().getAttribute("user");
		 logger.info("用户信息修改，操作人："+user.getName());
		 RespsonseResult result = new RespsonseResult();
		 try {
			 if(StringUtils.isBlank(querySysUser.getPassword())
					 && StringUtils.isBlank(querySysUser.getName())
					 && StringUtils.isBlank(querySysUser.getPic())
					 && StringUtils.isBlank(querySysUser.getCompanyInfo())
					 && StringUtils.isBlank( querySysUser.getPhone())){
				
				 result.setMsg("未输入修改信息");
				 return JSON.toJSON(result);    
			 }
			 if(user.getType() >3 ){
				 result.setMsg("权限不足");
				 return JSON.toJSON(result);
			 }
			 if(user.getType() !=0 ){
				 if(querySysUser.getType()<3){
					 result.setMsg("权限不足，非超级管理员，无法修改运维账号");
					 return JSON.toJSON(result);
				 }
				 if(user.getType() <3){
					 boolean bol = false ; 
					 QueryCompanyInfo qcInfo = new QueryCompanyInfo() ; 
					 qcInfo.setGroupCode(user.getCompanyInfo());
					 List< CompanyInfoDO >  companyData = companyInfoService.selectCompanyInfoList(qcInfo);
					 for(CompanyInfoDO each : companyData){
							if(querySysUser.getCompanyInfo().equals(each.getCompanyCode())){
								bol = true ;
								break ; 
							}
					}
					if(!bol){
						result.setMsg("权限不足,无法修改其他分组企业账号");
						return JSON.toJSON(result);
					}
				 }else{//企业人员修改
					 if(querySysUser.getType()<4 ||!querySysUser.getCompanyInfo().equals(user.getCompanyInfo()) ){
						 result.setMsg("权限不足，只能修改本企业普通账号");
						 return JSON.toJSON(result);
					 }
				 }
			 }
			 SysUserDO upUser = new SysUserDO(querySysUser);
			 upUser.setUserId(querySysUser.getUserId());
			 sysUserService.updateSysUserByUserId(upUser);
			 if(!StringUtils.isBlank(querySysUser.getName())){
				 serationLogService.upLogByUserId(upUser);
			 }
			 if(user.getType()<3){
				 insertLog(user,upUser,null,"修改账号信息");
			 }
			 result.setMsg("修改成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("修改出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
	}
	
	@RequestMapping("deluser")
	public @ResponseBody Object delUser(HttpServletRequest request,QuerySysUser querySysUser){
		 SysUserDO user = (SysUserDO) request.getSession().getAttribute("user");
 
		 logger.info("删除用户列表,操作人："+user);
		 RespsonseResult result = new RespsonseResult();
		 try {
			 if(StringUtils.isBlank(querySysUser.getCode())){
				 result.setMsg("账号信息为空信息");
				 return JSON.toJSON(result);    
			 }
			 QuerySysUser qsUser = new QuerySysUser();
			 qsUser.setCode(querySysUser.getCode());
			 SysUserDO delUser = sysUserService.selectOneSysUser(qsUser);
			 if(delUser == null){
				 result.setMsg("账号不存在");
				 return JSON.toJSON(result);   
			 }
			 if(delUser.getType()==0){
				 result.setMsg("超级管理员无法删除");
				 return JSON.toJSON(result);
			 }
			 if(!checkPermission(user,querySysUser)){
				 result.setMsg("权限不足");
				 return JSON.toJSON(result);    
			 }
			 SysUserDO upUser = new SysUserDO(querySysUser);
			// long userId = ;
			// System.out.println(delUser.getUserId());
			 upUser.setUserId(delUser.getUserId());
			 sysUserService.deleteSysUserByUserId(upUser);
			 if(user.getType() < 3){
				 insertLog(user,delUser,null,"删除账号");
			 }
			 result.setMsg("删除成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("删除出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("index")
	public @ResponseBody Object index(HttpServletRequest request){
		 logger.info("查询用户列表");
		 RespsonseResult result = new RespsonseResult();
		 try {
			 SysUserDO userInfo = (SysUserDO) request.getSession().getAttribute("user");
			 //查询出所有该分组下的人
			 List<String> companyCodes = new ArrayList<String>();
			 if(userInfo.getType() != 0){
				 result.setMsg("权限不足");
				 return JSON.toJSON(result);    
			 }
			 Map data = new HashMap();
			 //用户总数
			 int userNum = sysUserService.countSysUserList(new QuerySysUser());
			 data.put("userNum", userNum);
			 //操作记录数
			 int opNum = serationLogService.countSelectLog();
			 data.put("opNum", opNum);
			 //分组数
			 int groupNum = companyGroupInfoService.countCompanyGroupInfoList(new QueryCompanyGroupInfo());
			 data.put("groupNum", groupNum);
			 //企业总数
			 int companyNum = companyInfoService.countCompanyInfoList(new QueryCompanyInfo());
			 data.put("companyNum", companyNum);
			 
			 //数据更新数
			 data.put("dataUpNum", 0);
			 
			 data.put("accessNum", SysInfoUtil.userNumber);
			 
			 data.put("warningNum", 0);
			 
			 List mon = new ArrayList();
			 SimpleDateFormat dfd = new SimpleDateFormat("yyyy-MM");
			 Calendar a=new GregorianCalendar();
			 Map first = new HashMap();
			 first.put("month",dfd.format(a.getTime()));
			 first.put("num", 0);
			 mon.add(first);
			 for(int i =1;i<12;i++){
				 Map m = new HashMap();
				 a.add(Calendar.MONTH, -1);
				 m.put("month",dfd.format(a.getTime()));
				 m.put("num", i);
				 mon.add(m);
			 }
			 data.put("excessiveInfo", mon);
			 result.setData(data);
			 result.setMsg("查询成功");
			 result.setCode("0");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("查询出错");
			result.setCode("1");
		}
		return JSON.toJSON(result);    
	}
	
	
	@RequestMapping("exitSys")
	public @ResponseBody Object exitSys(HttpServletRequest request,QuerySysUser querySysUser){
		logger.info("退出登录");
		 RespsonseResult result = new RespsonseResult();
		 try {
			 request.getSession().setAttribute("user", null);
			 result.setCode("0");
			 result.setMsg("退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("退出失败");
			result.setCode("1");
		}
		return result;
	}
	
	
	@RequestMapping("notify")
	public @ResponseBody Object notify(HttpServletRequest request,QuerySysUser querySysUser,String data){
		logger.info("退出登录");
		 RespsonseResult result = new RespsonseResult();
		 try {
			 request.getSession().setAttribute("user", null);
			 result.setCode("0");
			 result.setMsg("退出成功");
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("退出失败");
			result.setCode("1");
		}
		return result;
	}
	
	
	
	//@Value("${openurl}")
    private String url = "http://47.110.54.212:5001/";
    
	@RequestMapping("getuserbycode")
	public @ResponseBody Object getUser(HttpServletRequest request,String  code){
		logger.info("获取用户信息"+code);
		RespsonseResult result = new RespsonseResult();
		if(code!=null){
			//获取openId
			String openId = "";
			try {
    			openId =HttpClient.sendGetRequest(url+"userinfo?usercode="+code, null,new  HttpHeaders());
			} catch (Exception e) {
				System.out.println("获取openid 出错");
				e.printStackTrace();
				result.setMsg("获取openid 出错");
				return JSON.toJSON(result);    
			}
			//查询数据库
			QuerySysUser querySysUser = new QuerySysUser();
			querySysUser.setWxid(openId);
			SysUserDO data = sysUserService.selectOneSysUser(querySysUser);
			if(data != null){
				request.getSession().setAttribute("openId", openId);
				request.getSession().setAttribute("user", data);
				result.setData(data);
			}
			result.setCode("0");
			result.putOtherInfo("wxid", openId);
			result.setMsg("获取成功");

		}
		logger.info("获取用户信息成功"+JSON.toJSON(result));
		return JSON.toJSON(result);    
	}
	
	@RequestMapping("login")
	public @ResponseBody Object login(HttpServletRequest request,QuerySysUser querySysUser){
		 logger.info("用户登录或绑定"+querySysUser.getCode());
		 RespsonseResult result = new RespsonseResult();
		 try {
 				 if(StringUtils.isNotBlank(querySysUser.getUserCode())
 						 &&StringUtils.isNotBlank(querySysUser.getPassword())){
 					 QuerySysUser qsUser = new QuerySysUser();
 					 qsUser.setCode(querySysUser.getUserCode());
 					 qsUser.setCompanyInfo(querySysUser.getCompanyInfo());
 					 SysUserDO data = sysUserService.selectOneSysUser(qsUser);
// 					 if(data.getType()!=0 && StringUtils.isNotBlank(querySysUser.getCompanyInfo())){
// 						 result.setMsg("企业代码不能为空");
// 						 return JSON.toJSON(result);    
// 					 }
 					 if(data != null && data.getPassword().equals(querySysUser.getPassword()) ){
 						String openId = querySysUser.getWxid();
 						System.out.println("openId:"+openId);
 			 			 if(openId != null){
 			 				data.setWxid(openId);
 			 				sysUserService.updateSysUserByUserId(data);
 							request.getSession().setAttribute("openId", openId);
 			 			}
 							request.getSession().setAttribute("user", data);
 							//获取公司名
 							 if(data.getType() == 0 ){
 								data.setCompanyName("文马科技");
 							 }else if(data.getType()<3 ){
 								 QueryCompanyGroupInfo q =  new QueryCompanyGroupInfo();
 								 q.setGroupCode(data.getCompanyInfo());
 								 CompanyGroupInfoDO companyGroupInfoDO = companyGroupInfoService.selectOneCompanyGroupInfo(q);
 								 if(companyGroupInfoDO!=null)
 									 data.setCompanyName(companyGroupInfoDO.getGroupName()+"运维人员");
 							 }else{
 								 QueryCompanyInfo qcInfo = new QueryCompanyInfo();
 								 qcInfo.setCompanyCode(data.getCompanyInfo());
 								 CompanyInfoDO companyInfoDO = companyInfoService.selectOneCompanyInfo(qcInfo);
 								 if(companyInfoDO!= null){
 									data.setCompanyName(companyInfoDO.getCompanyName());
 								 }
 							 }
 							result.setMsg("登录成功");
 							result.setCode("0");
 							result.setData(data);
 							System.out.println("登录成功");
 							SysInfoUtil.userNumber = SysInfoUtil.userNumber + 1;
 					 }else{
 						 result.setMsg("登录失败，账号信息错误"); 
 					 }
 				 }else{
 					 result.setMsg("账号或密码不能为空");
 				 }
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("登录出错");
		}
		return JSON.toJSON(result);    
		
		
	}
	/**
	 * 权限加油
	 * @param opUser 操作人
	 * @param opEdUser 被操作人
	 * @return
	 */
	private boolean checkPermission(SysUserDO opUser,QuerySysUser opEdUser) {
		if(opUser.getType() == 0){
			return true;
		}
		if(opUser.getType() > opEdUser.getType()){
			 return false;    
		 }
		//如果被操作的是企业人员
		if(opEdUser.getType() > 2 ){
			//如果操作员是运维人员，查询企业分组下的所有企业代码
			if(opUser.getType() < 3){
				QueryCompanyInfo qcInfo = new QueryCompanyInfo() ; 
				qcInfo.setGroupCode(opUser.getCompanyInfo());
				List< CompanyInfoDO > data = companyInfoService.selectCompanyInfoList(qcInfo);
				for(CompanyInfoDO each : data){
					if(each.getGroupCode().equals(opUser.getCompanyInfo())){
						return true;
					}
				}
			}else if(opUser.getType() == 3 && opUser.getCompanyInfo().equals(opEdUser.getCompanyInfo()) ){
				return true;
			}
		}
		//运维人员
		else if(opEdUser.getType() < 3 ){
			if(opUser.getCompanyInfo().equals(opEdUser.getCompanyInfo()) ){
				return true;
			}
		}
		return false;
		
	}
	public static void main(String[] args) {
		SysUserController s = new SysUserController();
		List<test> data= new ArrayList<>();
		data.add(s.new test("1", "超标1"));
		data.add(s.new test("2", "超标2"));
		Map m = new HashMap<>();
		m.put("data", data);
		System.out.println(JSON.toJSON(m));    
	}
	class test{
		String openId;
		String info ; 
		public test(String id ,String info){
			this.openId = id ;
			this.info = info ;
					
		}
		public String getOpenId() {
			return openId;
		}
		public void setOpenId(String openId) {
			this.openId = openId;
		}
		public String getInfo() {
			return info;
		}
		public void setInfo(String info) {
			this.info = info;
		}
		
	}
	public void insertLog(SysUserDO userInfo,SysUserDO data,SysUserDO dataed,String msg){
		try {
			 PerationLogDo PerationLogDo = new PerationLogDo();
			 PerationLogDo.setPerationUserId(userInfo.getUserId()+"");
			 PerationLogDo.setPerationUserName(userInfo.getName());
			 if(data!=null){
				 PerationLogDo.setPerationInfo(data.toString());
				 PerationLogDo.setPerationType(msg+data.getName());
			 }
			 if(dataed!=null){
				 PerationLogDo.setPerationInfoBefore(dataed.toString());
			 }
			 PerationLogDo.setPerationTime(new Timestamp(System.currentTimeMillis()));
			 serationLogService.insert(PerationLogDo);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("修改成功，但是插入日志失败");
		}
	}
	
}
